package job_guidline_handler

import (
	"net/http"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	"peilian-api/utils/format"
	"peilian-api/utils/paginate"
	"strconv"

	"github.com/gin-gonic/gin"
)

func GetExperience(c *gin.Context) {
	s := c.Query("type")
	careerId := c.Param("careerId")
	whereStr := "career_id = ?"
	if careerId == "0" {
		whereStr = "career_id <> ?"
	}
	var typ int = 1
	if len(s) != 0 {
		typ, _ = strconv.Atoi(s)
	}
	var experiences = []tables.Experience{}
	if err := variable.DB.MySQL.Scopes(paginate.Paginate(c.Request)).
		Where(whereStr, careerId).Where("type = ?", typ).Order("updated_at desc, created_at desc").
		Find(&experiences).Error; err != nil {
		format.NewResponseJson(c).Error(400, err.Error())
		return
	}
	var totalCount int64
	if err := variable.DB.MySQL.Model(&tables.Experience{}).
		Where(whereStr, careerId).Where("type = ?", typ).Count(&totalCount).Error; err != nil {
		format.NewResponseJson(c).Error(400, err.Error())
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"data":  experiences,
		"msg":   "ok",
		"total": totalCount,
	})
}

func GetAvailCareer(c *gin.Context) {
	subQuery := variable.DB.MySQL.Model(&tables.Experience{}).Distinct("career_id")
	careers := make([]*tables.Career, 0)
	if err := variable.DB.MySQL.Where("id in (?)", subQuery).Order("order_id").Find(&careers).Error; err != nil {
		format.NewResponseJson(c).Error(400, err.Error())
		return
	}
	allCareers := make([]*tables.Career, 0)
	allCareers = append(allCareers, &tables.Career{Name: "全部"})
	allCareers = append(allCareers, careers...)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": allCareers,
		"msg":  "ok",
	})
}
